package linkedlist;


/**
 * Created with IntelliJ IDEA.
 * Description: 206.反转链表
 * User: Li_yizYa
 * Date: 2025—03—24
 * Time: 23:08
 */
public class Solution2 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = null;
        ListNode ret = reverse(node1);
        while (ret != null) {
            System.out.print(ret.val + " ");
            ret = ret.next;
        }
    }

    /**
     * 递归实现（前到后）
     * @param head
     * @return
     */
    public static ListNode reverse(ListNode head) {
        return reverseList(null, head);
    }

    public static ListNode reverseList(ListNode pre, ListNode head) {
        if (head == null) {
            return pre;
        }
        ListNode next = head.next;
        head.next = pre;
        return reverseList(head, next);
    }

    /**
     * 非递归实现
     * @param head
     * @return
     */
    public static ListNode reverse1(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode pre = null;
        ListNode next = null;
        ListNode cur = head;

        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }
}
